#!/usr/bin/python
# -*- coding: utf-8 -*-

exec("import applications.%s.modules.apihelper as api" % request.application)

# store priority & status values in global vars
status_options=[OPTION(x.name, _value=x.id) for x in db().select(db.status.ALL)]
priority_options=[OPTION(x.name, _value=x.id) for x in db().select(db.priority.ALL)]
        
# ###########################################################
# ## generate menu
# ###########################################################

_f = request.function
approot='/%s/default/' % request.application
if not auth.user:
    response.menu = [(T('login'), True, '%slogin' % approot)]
    response.menu.append((T('register'), False, '%sregister' % approot))
else:
    response.menu = [(T('logout'), False, '%slogout' % approot)]
                          
if auth.is_logged_in():
    response.menu.append((T('profile'), _f=='profile','%sprofile' % approot))
    response.menu.append((T('create'), _f=='create','%screate' % approot))
    response.menu.append((T('mycases'), _f=='mycases','%smycases' % approot))
    #is the user agent or an admin?
    if auth.has_membership(db((db.auth_group.role=='agents')).select(db.auth_group.ALL)[0].id,auth.user.user_id):
        response.menu.append((T('workitems'), _f=='workitems','%sworkitems' % approot))
    if auth.has_membership(db((db.auth_group.role=='admin')).select(db.auth_group.ALL)[0].id,auth.user.user_id):
        response.menu.append((T('workitems'), _f=='workitems','%sworkitems' % approot))
        response.menu.append((T('assign'), _f=='assign','%sassign' % approot))


#response.menu.append((T('help'), False, '/'))

# ###########################################################
# ## title & keywords
# ###########################################################
response.title = 'Y-A-T-S-Y'
response.keywords = 'yatsy, Python, web2py, appengine, helpdesk, service desk'
response.description = 'a helpdesk application for google appengine'

# ###########################################################
# ## controller functions
# ###########################################################
def index():        
    response.flash="Welcome to YATSY"
    return dict()

#to create a case
@auth.requires_login()
def create():
    """
    create case; access to all; but needs a login
    """
    form=FORM(TABLE(TR("Title:",INPUT(_type="text",_name="title", requires=IS_NOT_EMPTY())),
            TR("Status:", api.get_default_status(db)),
            TR("Priority:", SELECT(_name='priority', value=api.get_default_priority(db), *priority_options)),
            TR("Description:", TEXTAREA(_name='description')),
            TR("Created By:", auth.user.email),
            TR("",INPUT(_type="submit", _value="Create"))
        ))
    if form.accepts(request.vars, session):
        #insert into the record
        uid = db(db.auth_user.email==auth.user.email).select(db.auth_user.ALL)
        api.create_case(db=db,
                    title=form.vars.title,
                    status=api.get_default_status_id(db),
                    priority=form.vars.priority,
                    created_via='web',
                    desc=form.vars.description,
                    created_by=uid[0].id,
                    created_at=request.now,
                    last_modified_by=uid[0].id,
                    last_modified_at=request.now)
        redirect(URL(r=request, f='index'))
    return dict(form=form)

@auth.requires_login()
def mycases():
    uid = db(db.auth_user.email==auth.user.email).select(db.auth_user.ALL)
    created_by = (db.cases.created_by==uid[0].id)
    return dict(mycases=api.get_cases(db=db, filter=created_by))
 

@auth.requires_login()
def workitems():
    uid = db(db.auth_user.email==auth.user.email).select(db.auth_user.ALL)
    assigned_to = (db.cases.assigned_to==uid[0].id)
    return dict(workitems=api.get_cases(db=db, filter=assigned_to))
    
@auth.requires_membership('admin')
def assign():
    #all unassigned cases
    return dict(records=api.get_cases(db=db, filter=db.cases.assigned_to==None))

@auth.requires_membership('admin')
def allcases():
    return dict(records=api.get_all_cases(db))
    
@auth.requires_login()
def addnotes():
    """
    displays case + notes for user who created
    user can't edit case details; can add notes
    """
    id=request.args[0]    
    case_value=api.get_case_details(db, case_id=id)
    if not len(case_value): redirect(URL(r=request, f='index'))

    noteform=FORM(TABLE(TR(TEXTAREA(_name="notes", requires=IS_NOT_EMPTY())),
                    TR(INPUT(_type="submit", _value="Create Note"))
                ))
    noteform.vars.case_id=id
    
    if noteform.accepts(request.vars,session):
        uid = db(db.auth_user.email==auth.user.email).select(db.auth_user.ALL)[0].id
        api.add_notes(db=db,author=uid, body=noteform.vars.notes, created_via='web',created_time=request.now, case_id=id)
        response.flash="successfully posted notes"
    notes=api.get_notes_for_case(db,case_id=id)
    return dict(case=case_value, notes=notes, noteform=noteform)
    

@auth.requires_login()
def editcase():
    """
    display case for the agent / admin with full edit access
    display all the notes too
    """
    id=request.args[0]
    case_value=api.get_case_details(db, case_id=id)
    if not len(case_value): redirect(URL(r=request, f='index'))
    #get the list of agents to be displayed in assigned_to drop down
    agents=api.get_agents(db)
    
    caseform=FORM()
    #if the current user is admin, give full access; if agent, give selected edit access
    #if auth.has_membership(db(db.auth_group.role=='admin').select(db.auth_group.ALL)[0].id,auth.user.id):
    #build an edit form
    caseform=FORM(TABLE(TR("Title:",case_value['title']),
            TR("Status:", SELECT(_name='status', value=case_value['status_id'] if case_value['status_id'] else api.get_default_status_id, *status_options)),
            TR("Priority:", SELECT(_name='priority', value=case_value['priority_id'] if case_value['priority_id'] else api.get_default_priority_id, *priority_options)),
            TR("Description:", case_value['description']),
            TR("Created By:", case_value['created_by']),
            TR("Assigned To:", SELECT(agents, _name='assigned_to', value=case_value['assigned_to'] if case_value['assigned_to'] else agents[0])),
            TR("",INPUT(_type="submit", _value="Update"))
    ))
    
    notes=api.get_notes_for_case(db,case_id=id)
                        
    if caseform.accepts(request.vars,session):
        #update the record
        uid = db(db.auth_user.email==caseform.vars.assigned_to).select(db.auth_user.ALL)
        db(db.cases.id==id).update(priority=caseform.vars.priority, status=caseform.vars.status, assigned_to=uid[0].id)
        redirect(URL(r=request,f='assign'))
                        
    return dict(caseform=caseform, notes=notes, case=case_value)

def login(): 
    return dict(form=auth.login(next='index'))

def logout():
    return dict(form=auth.logout(next='index'))

def register():
    return dict(form=auth.register(next='index'))
    
def profile():
    return dict(form=auth.profile())
